import { getToken } from '@/utils/token'
import CompetitionManagement from '@/views/layout/competitionManagement.vue'
import Layout from '@/views/layout/layout.vue'
import TopicManagement from '@/views/layout/topicManagement.vue'
import UpdateExam from '@/views/layout/UpdateExam.vue'
import UserManagement from '@/views/layout/userManagement.vue'
import Login from '@/views/login.vue'
import { ElMessage } from 'element-plus'
import { createRouter, createWebHistory } from 'vue-router'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      component:Login
    },
    {
      path: '/layout',
      component: Layout,
      redirect:'/layout/user',
      children: [
        {
          path: 'user',
          component: UserManagement
        },
        {
          path: 'topic',
          component: TopicManagement
        },
        {
          path: 'competition',
          component: CompetitionManagement
        },
        {
          path: 'updateExam',
          component:UpdateExam
        }
      ]
    },
    {
      path: '/',
      redirect:'/login'
    }
  ],
})
router.beforeEach((to, from, next) => {
  if (getToken()) {
    if (to.path == '/login') {
      next({ path: '/layout' })
    } else {
      next()
    }
  } else {
    if (to.path !== '/login') {
      ElMessage.warning("请先登录")
      next({
        path:'/login'
      })
    } else {
      next()
    }
  }
})
export default router
